package com.spzx.cloud.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.spzx.cloud.entity.User;
import com.spzx.cloud.user.handler.CustomerBlockHandler;
import com.spzx.cloud.user.result.Result;
import com.spzx.cloud.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/user")
@RefreshScope
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
//    private PatternProperties patternProperties;

    @Value("${pattern.dateformat}")
    private String pattern;

    // 兜底方法参数,要和 Controller 参数保持一致(包括返回值),并且要多加一个参数: BlockException
    public Result handleException(Long userId, BlockException exception) {
        return Result.build(null, 201, "失败了..");
    }

    @GetMapping(value = "/findUserByUserId/{userId}")
    // blockHandlerClass 属性是自定义限流处理类, blockHandler 是自定义限流处理类里面的方法名称
    @SentinelResource(value = "hot", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException")
    public Result findUserByUserId(@PathVariable(value = "userId") Long userId) {
        if (userId == 2) {
            throw new RuntimeException("手动抛出异常，触发异常比例熔断规则");
        }
        User user = this.userService.findUserByUserId(userId);
        return Result.build(user, 200, "success");
    }

    // 修改用户数据端点
    @GetMapping(value = "/updateUserById")
    public String updateUserById() {
        return "修改用户数据成功";
    }

    @GetMapping(value = "/save")
    public String save() {
        userService.queryUsers();
        System.out.println("保存用户");
        return "订单保存成功";
    }

    @GetMapping(value = "/query")
    public String query() {
        userService.queryUsers();
        System.out.println("查询用户");
        return "查询用户成功";
    }

}